using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ComponentModel;
using System.Data;
using ACME.Northwind.DataTransfer;
using ACME.Northwind.Business.Objects;
using Widgetsphere.Core.DataAccess;
using System.Linq.Expressions;
using ACME.Northwind.Business.LINQ;
using Widgetsphere.Core.Util;

namespace ACME.Northwind.DALProxy.Extensions
{
	/// <summary>
	/// This is a set of extensions for the Customer DAL/DTO object
	/// </summary>
	public static partial class CustomerExtension
	{
		#region Fill DAL

		/// <summary>
		/// Populate a DAL object from its corresponding DTO.
		/// </summary>
		/// <param name="item">The empty DAL object.</param>
		/// <param name="dtoItem">The source DTO to load.</param>
		public static void Fill(this Customer item, CustomerDTO dtoItem)
		{
			if (dtoItem == null) throw new Exception("The Customer DTO cannot be null.");
			if (item == null) throw new Exception("The Customer item cannot be null.");
			DataRow dr = ((DataRow)((IWrappingClass)item).WrappedClass);
			if (dtoItem.Region == null) dr["Region"] = System.DBNull.Value;
			else dr["Region"] = dtoItem.Region;
			if (dtoItem.PostalCode == null) dr["PostalCode"] = System.DBNull.Value;
			else dr["PostalCode"] = dtoItem.PostalCode;
			if (dtoItem.Phone == null) dr["Phone"] = System.DBNull.Value;
			else dr["Phone"] = dtoItem.Phone;
			if (dtoItem.Fax == null) dr["Fax"] = System.DBNull.Value;
			else dr["Fax"] = dtoItem.Fax;
			dr["CustomerID"] = dtoItem.CustomerId;
			if (dtoItem.Country == null) dr["Country"] = System.DBNull.Value;
			else dr["Country"] = dtoItem.Country;
			if (dtoItem.ContactTitle == null) dr["ContactTitle"] = System.DBNull.Value;
			else dr["ContactTitle"] = dtoItem.ContactTitle;
			if (dtoItem.ContactName == null) dr["ContactName"] = System.DBNull.Value;
			else dr["ContactName"] = dtoItem.ContactName;
			dr["CompanyName"] = dtoItem.CompanyName;
			if (dtoItem.City == null) dr["City"] = System.DBNull.Value;
			else dr["City"] = dtoItem.City;
			if (dtoItem.Address == null) dr["Address"] = System.DBNull.Value;
			else dr["Address"] = dtoItem.Address;
		}

		#endregion

		#region Fill DTO

		/// <summary>
		/// Populate a DTO object collection from its corresponding DAL object collection.
		/// </summary>
		/// <param name="list">The destination DTO collection.</param>
		/// <param name="customerCollection">The source DAL collection.</param>
		public static void Fill(this List<CustomerDTO> list, CustomerCollection customerCollection)
		{
			if (customerCollection == null) throw new Exception("The Customer collection cannot be null.");
			if (list == null) list = new List<CustomerDTO>();
			foreach (Customer item in customerCollection)
			{
				CustomerDTO newItem = new CustomerDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a DTO object from its corresponding DAL object.
		/// </summary>
		/// <param name="item">The source DAL object.</param>
		/// <param name="dtoItem">The empty DTO to load.</param>
		public static void Fill(this CustomerDTO dtoItem, Customer item)
		{
			if (dtoItem == null) throw new Exception("The Customer DTO cannot be null.");
			if (item == null) throw new Exception("The Customer item cannot be null.");
			dtoItem.Region = item.Region;
			dtoItem.PostalCode = item.PostalCode;
			dtoItem.Phone = item.Phone;
			dtoItem.Fax = item.Fax;
			dtoItem.CustomerId = item.CustomerId;
			dtoItem.Country = item.Country;
			dtoItem.ContactTitle = item.ContactTitle;
			dtoItem.ContactName = item.ContactName;
			dtoItem.CompanyName = item.CompanyName;
			dtoItem.City = item.City;
			dtoItem.Address = item.Address;
			dtoItem.CreatedDate = item.CreatedDate;
			dtoItem.CreatedBy = item.CreatedBy;
			dtoItem.ModifiedDate = item.ModifiedDate;
			dtoItem.ModifiedBy = item.ModifiedBy;
		}

		#endregion

		#region RunSelect

		/// <summary>
		/// Select all objects from store.
		/// </summary>
		public static void RunSelect(this List<CustomerDTO> list)
		{
			if (list == null) list = new List<CustomerDTO>();
			CustomerCollection retval = CustomerCollection.RunSelect();
			foreach (Customer item in retval)
			{
				CustomerDTO newItem = new CustomerDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<CustomerDTO> list, Expression<Func<CustomerQuery, bool>> where)
		{
			if (list == null) list = new List<CustomerDTO>();
			list.Fill(CustomerCollection.RunSelect(where));
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a paged result set.
		/// </summary>
		public static PagedQueryResults<CustomerDTO> RunSelect(this List<CustomerDTO> list, string pageSize, string page, string sortOrder, string sortColumn, string linq)
		{
			if (list == null) list = new List<CustomerDTO>();
			#region Setup Variables and Error Check
			int po;
			int rpp;

			if (!int.TryParse(page, out po)) throw new Exception("The page number number is not a valid integer!");
			if (po < 1) po = 1;

			if (!int.TryParse(pageSize, out rpp)) throw new Exception("The page size is not a valid integer!");
			if (rpp < 1) rpp = 1;

			Customer.FieldNameConstants sortField;
			try
			{
				sortField = (Customer.FieldNameConstants)Enum.Parse(typeof(Customer.FieldNameConstants), sortColumn);
			}
			catch
			{
				throw new Exception("The sort field is not valid!");
			}

			bool ascending = (sortOrder.ToLower() == "asc" || sortOrder.ToLower() == "ascending");
			#endregion

			PagedQueryResults<CustomerDTO> retVal = new PagedQueryResults<CustomerDTO>();
			CustomerPaging paging = new CustomerPaging();
			paging.RecordsperPage = rpp;
			paging.PageIndex = po;
			paging.OrderByList.Add(new CustomerPagingFieldItem(sortField, ascending));

			CustomerCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = CustomerCollection.RunSelect(x => true, paging);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodPaged(linq, "ACME.Northwind.Business", "Customer");
				dalList = (CustomerCollection)method.Invoke(null, new object[] { paging });
			}

			if (list == null) list = new List<CustomerDTO>();
			foreach (Customer item in dalList)
			{
				CustomerDTO newItem = new CustomerDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}

			retVal.CurrentPage = paging.PageIndex;
			double totalPages = Math.Ceiling((double)paging.RecordCount / (double)paging.RecordsperPage);
			retVal.TotalPages = (int)totalPages;
			retVal.TotalRecords = paging.RecordCount;
			retVal.GridData = list;

			return retVal;
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<CustomerDTO> list, string linq)
		{
			if (list == null) list = new List<CustomerDTO>();

			CustomerCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = CustomerCollection.RunSelect(x => true);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodAll(linq, "ACME.Northwind.Business", "Customer");
				dalList = (CustomerCollection)method.Invoke(null, new object[] { });
			}

			if (list == null) list = new List<CustomerDTO>();
			foreach (Customer item in dalList)
			{
				CustomerDTO newItem = new CustomerDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		#endregion

		#region Persist

		/// <summary>
		/// Persists this object to store.
		/// </summary>
		public static CustomerDTO Persist(this CustomerDTO customer)
		{
			if (customer == null) throw new Exception("The Customer DTO cannot be null.");
			//Find this object and if not exists, create a new one
			Customer newItem = null;
			CustomerCollection newCollection = null;

			bool isIdentityChecked = false;
			if (false) {}
			else
			{
				newItem = ACME.Northwind.Business.Objects.Customer.SelectUsingPK(customer.CustomerId);
				if (newItem == null)
				{
					newCollection = new CustomerCollection();
					newItem = newCollection.NewItem();
				}
				else
				{
					newCollection = newItem.ParentCollection;
				}
			}

			//Populate the DAL and perist
			newItem.Fill(customer);
			if (!newItem.IsParented) newCollection.AddItem(newItem);
			newCollection.Persist();

			//Re-populate the passed-in object from the DAL
			customer.Fill(newItem);
			return customer;
		}

		/// <summary>
		/// Persists this collection to store.
		/// </summary>
		public static bool Persist(this List<CustomerDTO> customerList)
		{
			if (customerList == null) throw new Exception("The Customer DTO list cannot be null.");
			//Get all objects from the database that match PK
			CustomerCollection customerCollection = new CustomerCollection();
			List<CustomerPrimaryKey> keyList = new List<CustomerPrimaryKey>();
			foreach (CustomerDTO dto in customerList)
			{
				keyList.Add(new CustomerPrimaryKey(dto.CustomerId));
			}			
			customerCollection.SubDomain.AddSelectCommand(new ACME.Northwind.Business.SelectCommands.CustomerSelectByPks(keyList));
			customerCollection.SubDomain.RunSelectCommands();

			//Now find and populate the objects for saving
			foreach (CustomerDTO dto in customerList)
			{
				Customer customer = (from x in (IEnumerable<Customer>)customerCollection
					where x.CustomerId == dto.CustomerId
					select x).FirstOrDefault();

				if (customer == null) customer = customerCollection.NewItem();
				customer.Fill(dto);
				if (!customer.IsParented) customerCollection.AddItem(customer);
			}
			customerCollection.Persist();

			//Re-populate the passed-in object from the DAL
			List<CustomerDTO> deletedList = new List<CustomerDTO>();
			foreach (CustomerDTO dto in customerList)
			{
				Customer customer = (from x in (IEnumerable<Customer>)customerCollection
					where x.CustomerId == dto.CustomerId
					select x).FirstOrDefault();

				if (customer != null) dto.Fill(customer);
				else deletedList.Add(dto);
			}

			//Remove the items that are no longer there (if any)
			foreach (CustomerDTO dto in deletedList)
			{
				customerList.Remove(dto);
			}

			return true;
		}

		#endregion

		#region Customer Select by Column

		/// <summary>
		/// Select an object list by 'City' field.
		/// </summary>
		public static void SelectByCityField(this List<CustomerDTO> customerList, string city)
		{
			CustomerCollection list = CustomerCollection.SelectByCity(city);
			foreach (Customer item in list)
			{
				CustomerDTO newItem = new CustomerDTO();
				newItem.Fill(item);
				customerList.Add(newItem);
			}
		}

		#endregion

		#region Customer SelectUsingPK

		/// <summary>
		/// Select a single object from this collection by its primary key.
		/// </summary>
		public static bool SelectUsingPK(this CustomerDTO customer, string customerid)
		{
			Customer item = ACME.Northwind.Business.Objects.Customer.SelectUsingPK(customerid);
			if (item == null) return false;
			customer.Fill(item);
			return true;
		}

		#endregion

		#region Customer Select By Foreign Key

		#endregion

		#region Customer Delete

		/// <summary>
		/// Delete the specified item
		/// </summary>
		public static bool Delete(this CustomerDTO customer)
		{
			Customer item = ACME.Northwind.Business.Objects.Customer.SelectUsingPK(customer.CustomerId);
			if (item == null) return false;
			item.Delete();
			item.Persist();
			return true;
		}

		#endregion
	}

}
